package com.liu.share.util;

import java.io.*;

/**
 * @Auther: liucongcong
 * @Date: 2019/3/24
 * @Description:
 */
public class SeriallizeUtil {

    public static void seriallizeObject(Object object,String filePath) throws IOException {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filePath)));
        objectOutputStream.writeObject(object);
        System.out.println("序列化成功");
    }

    public static Object deSerializeObject(String filePath) throws IOException ,ClassNotFoundException{
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(filePath)));
        return objectInputStream.readObject();
    }

    public static void main(String[] args) {
        Person person = new Person("柳聪",24,"湖北");
        try {
            seriallizeObject(person,"E:/Person.txt");

            Person person1 = (Person) deSerializeObject("E:/Person.txt");
            System.out.println(person == person1);
            System.out.println(person1);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private static class Person implements Serializable{
        private String name;

        private int age;

        private String address;

        public Person(String name,int age,String address){
            this.address = address;
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", address='" + address + '\'' +
                    '}';
        }
    }

}
